$(document).ready(function() {
	
	$(function() {
		$("#tabs").tabs();
		$("#editor-container").resizable({ handles: 's', alsoResize: 'iframe' });
		$( "button, input:submit, a").button();
//		$( "a", ".demo" ).click(function() { return false; });
		// http://localhost:8080/pentaho/content/console/index.html?source=PUC&id=fileid
	});
	
	$("#save").click(function(event) {
		var scriptId = $.url.param("id")
		$.ajax({
		   	type: "PUT",
		    url: "/pentaho/plugin/cws/api/repo/files/"+scriptId+"/data",
		    data: editor.getCode(),
		    contentType: "text/plain",
			
		    success: function() {
		    	alert("Save Successful");
		    },

			error: function (XMLHttpRequest, textStatus, errorThrown) {
				alert("Error saving file: " + errorThrown);
			}

		});
	});

    $("#execute").click(function(event) {
		$.ajax({
		   	type: "POST",
		    url: "/pentaho/plugin/groovy/api/console/script",
		    data: { script: editor.getCode() },
			dataType: "json",
			
		    success: function(data) {
				$('#output').text("");
				$('#result').text("");
				$('#error').text("");
				
				if (data.outputText.length > 0) {
					$("#tabs").tabs('select', 1);
					$('#output').text(data.outputText).fadeIn();
				} else {
					$('#output').fadeOut();
				}

				if (data.executionResult.length > 0) {
					if (data.executionResult != "null") {
						$("#tabs").tabs('select', 0);
					}
					$('#result').text(data.executionResult).fadeIn();
				} else {
					$('#result').fadeOut();
				}
				
				if (data.stacktraceText.length > 0) {
					$("#tabs").tabs('select', 2);
					$('#error').text(data.stacktraceText).fadeIn();
				} else {
					$('#error').fadeOut();
				}
		    },

			error: function (XMLHttpRequest, textStatus, errorThrown) {
				alert("Error interacting with the Groovy web console server: " + errorThrown);
			}

		});
    });
});



